import { Member, administrator, ADMINISTRATOR } from '../../src/lib/Member'
import {ClsMember} from "../model";
import {ILike} from "typeorm";


export default async function(app, io) {
  const { socket } = app.locals;
  const { userId, username, userType } = socket.handshake.query;

  console.log('------------------- adminMiddleware -----------------------')
  const [dbUser, count] = await ClsMember.findAndCountBy({
    userType: ILike('%admin%')
  });

  for (const member of dbUser) {
    const adminClass = administrator.get(ADMINISTRATOR) ?? new Set();

    administrator.set(ADMINISTRATOR, adminClass.add(member as any))
  }



  /**
   * 如果这个人在管理组，则将这个人加入管理组。
   */
  if (userType && userType.startsWith('admin')) {
    socket.join(ADMINISTRATOR)
  }

  socket
    .broadcast
    .to(ADMINISTRATOR)
    .emit('online', { userId, username } as any);
  /*if (administrator.has(userId)) {
    for (const [classId, classroom] of (administrator)) {
      socket
        .broadcast
        .to(classId)
        .emit('online', {
          member: { userId, username }
        } as any);
    }
  }*/

  if (!socket.broadcastMemberForAdmin) {
    socket.broadcastMemberForAdmin = function broadcastMemberForAdmin(data) {
      console.warn(`member:state =>`, data)
      socket
        .broadcast
        .to(ADMINISTRATOR)
        .emit('member:state', data);
      /*for (const [classId, classroom] of (administrator)) {
        socket
          .broadcast
          .to(ADMINISTRATOR)
          .emit('member:state', data);
      }*/
    }
  }

  if (!socket.broadcastClassForAdmin) {
    socket.broadcastClassForAdmin = function broadcastClassForAdmin(data) {
      console.warn(`classroom:state =>`, data)
      socket
        .broadcast
        .to(ADMINISTRATOR)
        .emit('classroom:state', data);

      /*for (const [classId, classroom] of (administrator)) {
        socket
          .broadcast
          .to(classId)
          .emit('classroom:state', data);
      }*/
    }
  }
}
